<template>
  <div class="logo-title">租赁配置</div>
  <!-- 详情 -->
  <div class="logo-detail" v-if="status == 'view'">
    <a-row class="logo-info">
      <a-col :span="enterpriseDetail.wxNativePay == 1 ? 12 : 24">
        <div class="flex logo-info-item">
          <div class="logo-info-label">商户支持服务类型：</div>
          <div class="logo-info-content">
            <!-- sass 后台至少勾选了服务类型 -->
            <template v-if="serviceTypeMaps.length > 0 && userServiceTypeMaps.length > 0">
              {{ userServiceTypeMaps.map((item) => item.label).join('、') }}
            </template>
            <template v-else> 暂无 </template>
          </div>
        </div>
      </a-col>
      <!-- sass 后台开启了微信二维码收款 -->
      <a-col :span="12" v-if="enterpriseDetail.wxNativePay == 1">
        <div class="flex logo-info-item">
          <div class="logo-info-label">线上微信二维码收款：</div>
          <div class="logo-info-content">
            {{ enterpriseDetail.userWxNativePay == 1 ? '开启' : '关闭' }}
          </div>
        </div>
      </a-col>
      <!-- 自驾短租配置 -->
      <a-col :span="10" v-if="showDzConfig">
        <div class="item-block">
          <div class="flex logo-info-item">
            <div class="logo-info-label">自驾短租渠道配置：</div>
            <div class="logo-info-content">
              <template v-if="shortRentChannels.length > 0 && userShortRentChannels.length > 0">
                {{ userShortRentChannels.map((item) => item.label).join(' | ') }}
              </template>
              <template v-else> 暂无 </template>
            </div>
          </div>
          <template v-if="showChannelSync">
            <div class="flex logo-info-item">
              <div class="logo-info-label">渠道订单同步方式：</div>
              <div class="logo-info-content">
                {{ channelOrderSyncVal }}
              </div>
            </div>
            <div class="flex logo-info-item">
              <div class="logo-info-label">渠道订单维护方式：</div>
              <div class="logo-info-content">
                {{ channelOrderMaintenanceVal }}
              </div>
            </div>
          </template>
        </div>
      </a-col>
      <a-col :span="24">
        <div class="flex logo-info-item mt-2.5">
          <div class="logo-info-label">配置车辆整备时间：</div>
          <div class="logo-info-content">
            {{ enterpriseDetail.config.prepareStatusName }}
          </div>
        </div>
      </a-col>
      <a-col :span="10" v-if="enterpriseDetail.config.prepareStatus === 1">
        <div class="item-block">
          <div class="flex logo-info-item">
            <div class="logo-info-label">
              订单预计开始用车前 <span class="text-blue">{{ enterpriseDetail.config.prepareStartMinute }}</span> 分钟，为车辆整备时间
            </div>
          </div>
          <div class="flex logo-info-item">
            <div class="logo-info-label">
              订单预计结束用车后 <span class="text-blue">{{ enterpriseDetail.config.prepareEndMinute }}</span> 分钟，为车辆整备时间
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
  <!-- 编辑租赁配置 -->
  <div v-else>
    <page-form ref="formRef" :model="form" layout="vertical">
      <page-form-row>
        <page-form-item label="商户支持服务类型" size="1/2" v-if="serviceTypeMaps.length > 0" style="margin-bottom: 3px">
          <a-space :size="16">
            <template v-for="item in serviceTypeMaps" :key="item.value">
              <a-checkbox v-if="item.value == 1" v-model="form.dzServiceType" @change="(val) => serviceTypeChangeFn(val, item)">
                {{ item.label }}
              </a-checkbox>
              <a-checkbox v-if="item.value == 2" v-model="form.czServiceType" @change="(val) => serviceTypeChangeFn(val, item)">
                {{ item.label }}
              </a-checkbox>
            </template>
          </a-space>
        </page-form-item>
        <page-form-item label="线上微信二维码收款" size="1/2" v-if="enterpriseDetail.wxNativePay == 1">
          <a-radio-group v-model="form.userWxNativePay">
            <a-radio :value="item.value" v-for="item in dict.enterpriseWxNativePayEnum" :key="item.value">
              {{ item.label }}
            </a-radio>
          </a-radio-group>
        </page-form-item>
      </page-form-row>
      <!-- sass 后台配置了短租渠道 -->
      <a-row v-if="form.dzServiceType">
        <a-col :span="24">
          <div class="page-form-block">
            <page-form-item label="自驾短租渠道配置" size="1">
              <a-checkbox-group v-model="form.userShortRentChannels">
                <a-checkbox :value="item.value" v-for="item in shortRentChannels" :key="item.value">
                  {{ item.label }}
                </a-checkbox>
              </a-checkbox-group>
            </page-form-item>
            <template v-if="showChannelSync">
              <page-form-item label="渠道订单同步方式" size="1">
                <a-radio-group v-model="form.channelOrderSync">
                  <a-radio :value="item.value" v-for="item in channelOrderSyncList" :key="item.value">
                    {{ item.label }}
                  </a-radio>
                </a-radio-group>
              </page-form-item>
              <page-form-item label="渠道订单维护方式" size="1">
                <div>
                  <a-alert>
                    <template #icon>
                      <icon-exclamation-circle />
                    </template>
                    维护方式自动切换为手动，所有订单的维护方式变更为手动，所有历史订单将不在进行自动更新，订单后续支持操作。
                    <br />
                    维护方式手动切换为自动，历史订单仍为手动维护，新生成的订单为自动维护。
                  </a-alert>
                  <a-radio-group style="margin-top: 10px" v-model="form.channelOrderMaintenance">
                    <a-radio :value="item.value" v-for="item in channelOrderMaintenanceList" :key="item.value">
                      {{ item.label }}
                    </a-radio>
                  </a-radio-group>
                </div>
              </page-form-item>
            </template>
          </div>
        </a-col>
      </a-row>
      <page-form-row class="mt-2.5">
        <page-form-item label="配置车辆整备时间" size="1/2" style="margin-bottom: 3px">
          <a-space :size="16">
            <a-radio-group style="margin-top: 10px" v-model="form.prepareStatus">
              <a-radio :value="item.value" v-for="item in dict.enterprisePrepareStatusEnum" :key="item.value">
                {{ item.label }}
              </a-radio>
            </a-radio-group>
          </a-space>
        </page-form-item>
      </page-form-row>
      <a-row v-if="form.prepareStatus == 1">
        <a-col :span="24">
          <div class="page-form-block">
            <page-form-item size="1" field="prepareStartMinute" :rules="{ required: true, message: '请输入' }">
              订单预计开始用车前&nbsp;
              <a-input-number :max="99999" :min="0" placeholder="请输入" style="width: 150px" v-model="form.prepareStartMinute" hide-button>
                <template #suffix> 分钟 </template>
              </a-input-number>
              &nbsp;为车辆整备时间
            </page-form-item>
            <page-form-item size="1" field="prepareEndMinute" :rules="{ required: true, message: '请输入' }">
              订单预计结束用车后&nbsp;
              <a-input-number :max="99999" :min="0" placeholder="请输入" style="width: 150px" v-model="form.prepareEndMinute" hide-button>
                <template #suffix> 分钟 </template>
              </a-input-number>
              &nbsp;为车辆整备时间
            </page-form-item>
          </div>
        </a-col>
      </a-row>
    </page-form>
    <!-- 服务类型 checkbox 询问弹窗 -->
    <a-modal v-model:visible="serviceTypeModalVisible" ok-text="确认" @cancel="serviceTypeModalCancelFn" simple>
      <a-space :size="16" direction="vertical" fill>
        <p class="w-full text-center confirm-content">
          {{ `请确认是否${confirmOperateType ? '开启' : '关闭'}自驾${confirmServiceType == 1 ? '短租' : '长租'}服务？` }}
        </p>
        <p class="w-full text-center confirm-tips" v-if="!confirmOperateType">
          {{ `注：关闭后自驾${confirmServiceType == 1 ? '短租' : '长租'}的相关业务服务将不可用` }}
        </p>
      </a-space>
    </a-modal>
  </div>
</template>

<script setup name="EnterpriseRentConfig">
  import { ref, reactive, watch, inject, computed } from 'vue'
  import { saveEnterprise } from '@/api/asset/enterprise.js'
  const props = defineProps({
    status: String,
    enterpriseDetail: Object,
  })
  const dict = inject('dict')
  const channelOrderSyncList = ref([
    { label: '自动&手动', value: 1 },
    { label: '仅手动', value: 2 },
  ])
  const channelOrderMaintenanceList = ref([
    { label: '自动维护', value: 1 },
    { label: '手动维护', value: 2 },
  ])
  const channelOrderSyncVal = computed(() => {
    const sync = props.enterpriseDetail?.channelOrderSync
    if (!sync) return '-'
    return channelOrderSyncList.value.find((item) => item.value == sync).label
  })
  const showChannelSync = computed(() => {
    if (form.userShortRentChannels == null) return false
    // 2, 3, 4, 5, 6, 7   除0（小程序）开通了渠道同步
    return form.userShortRentChannels.some((item) => item >= 2)
  })
  const channelOrderMaintenanceVal = computed(() => {
    const maintenance = props.enterpriseDetail?.channelOrderMaintenance
    if (!maintenance) return '-'
    return channelOrderMaintenanceList.value.find((item) => item.value == maintenance).label
  })
  // saas 后台配置的服务类型
  const serviceTypeMaps = computed(() => {
    const dictMaps = dict.serviceTypeEnum
    const serviceTypes = props.enterpriseDetail?.serviceTypes
    if (serviceTypes && dictMaps) {
      return dictMaps.filter((item) => {
        return serviceTypes.includes(item.value)
      })
    }
    return []
  })
  // 当前商户选择的服务类型
  const userServiceTypeMaps = computed(() => {
    const userServiceTypes = props.enterpriseDetail?.userServiceTypes
    if (serviceTypeMaps.value && userServiceTypes) {
      return serviceTypeMaps.value.filter((item) => {
        return userServiceTypes.includes(item.value)
      })
    }
    return []
  })
  // saas 后台配置的渠道类型
  const shortRentChannels = computed(() => {
    const dictMaps = dict.shortRentChannelEnum
    const shortRentChannels = props.enterpriseDetail?.shortRentChannels
    if (shortRentChannels && dictMaps) {
      return dictMaps.filter((item) => {
        return shortRentChannels.includes(item.value)
      })
    }
    return []
  })
  // 当前商户选择的渠道类型
  const userShortRentChannels = computed(() => {
    const userShortRentChannels = props.enterpriseDetail?.userShortRentChannels
    if (shortRentChannels.value && userShortRentChannels) {
      return shortRentChannels.value.filter((item) => {
        return userShortRentChannels.includes(item.value)
      })
    }
    return []
  })
  const showDzConfig = computed(() => {
    // sass 后台配置了短租服务
    let sassDzFlag = userServiceTypeMaps.value.some((item) => item.value == 1)
    return sassDzFlag && form.dzServiceType
  })
  const emit = defineEmits(['updateData'])
  const form = reactive({
    epId: '',
    userServiceTypes: [],
    userShortRentChannels: [],
    userWxNativePay: '',
    epContactList: [],
    czServiceType: false,
    dzServiceType: false,
    prepareStartMinute: 0,
    prepareEndMinute: 30,
  })
  const formRef = ref()
  watch(
    () => props.enterpriseDetail,
    (newVal) => {
      form.epId = newVal.epId
      form.userServiceTypes = newVal.userServiceTypes
      form.userShortRentChannels = newVal.userShortRentChannels
      form.userWxNativePay = newVal.userWxNativePay
      form.epContactList = newVal.epContacts
      form.dzServiceType = newVal.userServiceTypes.includes(1)
      form.czServiceType = newVal.userServiceTypes.includes(2)
      form.channelOrderSync = newVal.channelOrderSync
      form.channelOrderMaintenance = newVal.channelOrderMaintenance
      form.prepareStatus = newVal.config.prepareStatus
      form.prepareStartMinute = newVal.config.prepareStartMinute
      form.prepareEndMinute = newVal.config.prepareEndMinute
    },
    { immediate: true }
  )
  // 取消
  const serviceTypeModalCancelFn = () => {
    if (confirmServiceType.value == 1) {
      form.dzServiceType = !confirmOperateType.value
    }
    if (confirmServiceType.value == 2) {
      form.czServiceType = !confirmOperateType.value
    }
  }
  const serviceTypeModalVisible = ref(false)
  // 开启 | 关闭 Boolean 值
  const confirmServiceType = ref()
  // 开启 | 关闭 Boolean 值
  const confirmOperateType = ref()
  const serviceTypeChangeFn = (val, item) => {
    confirmServiceType.value = item.value
    confirmOperateType.value = val
    serviceTypeModalVisible.value = true
  }
  // 保存
  const saveFn = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          console.log(error)
          reject()
        } else {
          let userServiceTypes = []
          if (form.dzServiceType) {
            userServiceTypes.push(1)
          }
          if (form.czServiceType) {
            userServiceTypes.push(2)
          }
          const param = {
            epId: form.epId,
            userServiceTypes: userServiceTypes,
            userShortRentChannels: form.userShortRentChannels,
            userWxNativePay: form.userWxNativePay,
            epContactList: form.epContactList,
            channelOrderSync: form.channelOrderSync,
            channelOrderMaintenance: form.channelOrderMaintenance,
            prepareStatus: form.prepareStatus,
            prepareStartMinute: form.prepareStartMinute,
            prepareEndMinute: form.prepareEndMinute,
          }
          saveEnterprise(param)
            .then((res) => {
              if (res.code == 200) {
                // 更新 enterpriseDetail 的值
                emit('updateData')
                resolve()
              }
            })
            .catch(() => {
              reject()
            })
        }
      })
    })
  }

  defineExpose({
    saveFn,
  })
</script>

<style lang="less" scoped>
  .text-blue {
    color: #165dff;
  }
  .logo-title {
    font-size: 16px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 16px;
  }
  .item-block {
    padding: 20px;
    margin-top: 10px;
    background: rgba(247, 248, 250, 0.5);
  }
  .logo-info-item {
    font-size: 14px;
    .logo-info-label {
      color: #4e5969;
      text-align: right;
    }
    .logo-info-content {
      color: #1d2129;
    }
  }
  .logo-info-item + .logo-info-item {
    margin-top: 8px;
  }
  .logo-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    float: left;
    width: 104px;
    height: 104px;
    margin-right: 8px;
    margin-bottom: 8px;
    background-color: #fafafa;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
    .plus {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: rgba(0, 0, 0, 0.65);
      .plus-text {
        font-size: 14px;
        margin-top: 8px;
      }
    }
  }
  .page-form-block {
    background: rgba(247, 248, 250, 0.5);
    padding: 20px;
    padding-bottom: 1px;
  }
  .confirm-content {
    margin-top: 10px;
  }
  .confirm-tips {
    color: rgb(var(--red-6));
  }
</style>
